package lang

import (
	"langtu.com/common/components/checksum"
	"strings"
)

type Password struct {
	//	密码
	PasswordValue string `json:"passwordValue"`
	//	密码对应的md5值
	PasswordMd5Value string `json:"password_md_5_value"`
	// 转换器
	Algorithm checksum.ISignatureAlgorithm
}

type PasswordNotMatchError struct {
}

func (e *PasswordNotMatchError) Error() string {
	return "Password is not match"
}

// NewPassword
//
//	@Description: 创建密码
//	@param PasswordValue
//	@return *Password
func NewPassword(PasswordValue string) Password {
	password := Password{
		PasswordValue:    PasswordValue,
		Algorithm:        &checksum.Algorithm4Md5{Upper: true},
		PasswordMd5Value: "",
	}
	password.PasswordMd5Value = password.Algorithm.Cal(password.PasswordValue)
	return password
}

// validate
//
//	@Description:  验证
//	@receiver p
//	@param strPassword
//	@return bool
func (p *Password) validate(strPassword string) bool {
	if len(strPassword) == 0 {
		return false
	}
	return strings.Compare(p.PasswordMd5Value, p.Algorithm.Cal(strPassword)) == 0
}

// Update
//
//	@Description: 修改密码
//	@receiver p
//	@param strPassword
//	@param originPasswordValue
//	@return error
func (p *Password) Update(strNewPassword string, originPasswordValue string) error {
	validate := p.validate(originPasswordValue)
	if !validate {
		return &PasswordNotMatchError{}
	}
	p.PasswordValue = strNewPassword
	p.PasswordMd5Value = p.Algorithm.Cal(strNewPassword)
	return nil
}

// forceUpdate
//
//	@Description: 	强制性修改密码
//	@receiver p
//	@param strNewPassword
func (p *Password) forceUpdate(strNewPassword string) {
	p.PasswordValue = strNewPassword
	p.PasswordMd5Value = p.Algorithm.Cal(strNewPassword)
}
